package com.szxy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szxy.constants.Constants;
import com.szxy.domain.DictData;
import com.szxy.domain.DictType;
import com.szxy.dto.DictTypeDto;
import com.szxy.mapper.DictDataMapper;
import com.szxy.mapper.DictTypeMapper;
import com.szxy.service.DictTypeService;
import com.szxy.vo.DataGridView;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: zwz
 * @Date:2020/11/5 21:01
 * @Description: 数据字典服务
 **/
@Service
public class DictTypeServiceImpl implements DictTypeService {

    @Autowired
    private DictTypeMapper dictTypeMapper;
    @Autowired
    private DictDataMapper dictDataMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public DataGridView listPage(DictTypeDto dictTypeDto) {
        // 分页
        Page<DictType> page = new Page<>(dictTypeDto.getPageNum(), dictTypeDto.getPageSize());
        // 请求参数
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotBlank(dictTypeDto.getDictType()), DictType.COL_DICT_TYPE, dictTypeDto.getDictType());
        qw.like(StringUtils.isNotBlank(dictTypeDto.getDictName()), DictType.COL_DICT_NAME, dictTypeDto.getDictName());
        qw.eq(StringUtils.isNotBlank(dictTypeDto.getStatus()), DictType.COL_STATUS, dictTypeDto.getStatus());
        qw.ge(null != dictTypeDto.getBeginTime(), DictType.COL_CREATE_TIME, dictTypeDto.getBeginTime());
        qw.lt(null != dictTypeDto.getEndTime(), DictType.COL_CREATE_TIME, dictTypeDto.getEndTime());
        // 查询
        dictTypeMapper.selectPage(page, qw);
        return new DataGridView(page.getTotal(), page.getRecords());
    }

    @Override
    public DataGridView list() {
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        // 只看可用的
        qw.eq(DictType.COL_STATUS, Constants.STATUS_TRUE);
        return new DataGridView(null, dictTypeMapper.selectList(qw));
    }

    @Override
    public Boolean checkDictTypeUnique(Long dictId, String dictType) {
        dictId = (dictId == null) ? -1 : dictId;
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        qw.eq(DictType.COL_DICT_TYPE, dictType);
        DictType dt = dictTypeMapper.selectOne(qw);
        if (null != dt && dictId.longValue() != dt.getDictId()) {
            return true; // 不存在
        }
        return false; // 存在
    }

    @Override
    public int insert(DictTypeDto dictTypeDto) {
        DictType dictType = new DictType();
        // hutool 复制属性
        BeanUtil.copyProperties(dictTypeDto, dictType);
        // 组装
        dictType.setCreateBy(dictTypeDto.getSimpleUser().getUserName());
        dictType.setCreateTime(new Date());
        return dictTypeMapper.insert(dictType);
    }

    @Override
    public int update(DictTypeDto dictTypeDto) {
        DictType dictType = new DictType();
        // 复制属性
        BeanUtil.copyProperties(dictTypeDto, dictType);
        // 组装
        dictType.setUpdateBy(dictTypeDto.getSimpleUser().getUserName());
        return dictTypeMapper.updateById(dictType);
    }

    @Override
    public int deleteDictTypeByIds(Long[] dictIds) {
        List<Long> idsList = Arrays.asList(dictIds);
        if (null != idsList && idsList.size() > 0) {
            return dictTypeMapper.deleteBatchIds(idsList);
        }
        return -1;
    }

    /**
     *   查询所有 dictType ， 再根据每个 dictType ，查询出对应字典数据
     *
     *   redis 键的设计：dict:dictType -> [{},{}]
     */
    @Override
    public void dictCacheSync() {
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        qw.eq(DictType.COL_STATUS, Constants.STATUS_TRUE);
        this.dictTypeMapper.selectList(qw)
                .stream()
                .map(DictType::getDictType)
                .forEach(dictType -> {
                    QueryWrapper<DictData> qdw = new QueryWrapper<>();
                    qdw.eq(DictData.COL_STATUS, Constants.STATUS_TRUE);
                    qdw.eq(DictData.COL_DICT_TYPE, dictType);
                    List<DictData> dictDataList = dictDataMapper.selectList(qdw);
                    this.stringRedisTemplate
                        .opsForValue()
                        .set(Constants.DICT_REDIS_PROFIX+dictType, JSON.toJSONString(dictDataList));
        });
    }

    @Override
    public DictType selectDictTypeById(Long dictId) {
        return dictTypeMapper.selectById(dictId);
    }
}
